import React, {useEffect, useState} from "react";
import {Button, Col, DatePicker, Form, Input, InputNumber, message, Modal, Row, Select} from "antd";
import type {Result} from "@/types/result";
import jobDescriptionApi from "@/api/jobDescriptionApi.ts";
import {JobDescription} from "@/types/resp/jobDescription";
import EnterpriseSelector from "@/pages/enterprise/EnterpriseSelector.tsx";
import DepartmentSelector from "@/pages/department/DepartmentSelector.tsx";

interface JobDescriptionAddProps {
  visible: boolean;
  id: number;
  onCloseJobDescriptionAdd: () => void;
}

const JobDescriptionAdd: React.FC<JobDescriptionAddProps> = ({visible, id, onCloseJobDescriptionAdd}) => {

  const [form] = Form.useForm<JobDescription>();
  const [messageApi, messageContextHolder] = message.useMessage();

  const rules = {
    enterpriseName: [
      { required: true, message: '请输入企业名称' }
    ],
    jobTitle: [
      { required: true, message: '请输入岗位名称' }
    ],
    departmentName: [
      { required: true, message: '请输入部门名称' }
    ],
    workLocation: [
      { required: true, message: '请输入工作地点' }
    ],
    jobType: [
      { required: true, message: '请输入岗位类型' }
    ],
    responsibilities: [
      { required: true, message: '请输入岗位职责' }
    ],
    requirement: [
      { required: true, message: '请输入岗位要求' }
    ],
    salaryRange: [
      { required: true, message: '请输入薪资范围' }
    ],
    postingDate: [
      { required: true, message: '请输入发布日期' }
    ],
    headCount: [
      { required: true, message: '请输入招聘人数' }
    ],
    status: [
      { required: true, message: '请输入状态' }
    ],
  };

  let jobDescriptionForm: Partial<JobDescription> = {}

  const [title, setTitle] = useState('新增招聘岗位');

  useEffect(() => {
    if (!visible) {
      return
    }
    if (id) {
      setTitle('编辑招聘岗位')
      initJobDescriptionFormById(id)
    } else {
      setTitle('新增招聘岗位')
      form.resetFields();
    }
  }, [visible]);

  const initJobDescriptionFormById = async (id: number) => {
    const resp: Result<JobDescription> = await jobDescriptionApi.findById(id)
    if (resp && resp.code === 1 && resp.data) {
      jobDescriptionForm = resp.data
      form.setFieldsValue(resp.data);
    }
  }

  const onSave = async () => {
    try {
      await form.validateFields()

      let jobDescription2Save:JobDescription = form.getFieldsValue()
      if (id) {
        jobDescription2Save = Object.assign(jobDescriptionForm, jobDescription2Save)
      }
      const resp: Result<void> = await jobDescriptionApi.save(jobDescription2Save);
      if (!resp || resp.code !== 1) {
        messageApi.error('保存失败:' + (resp.msg ? resp.msg : '未知异常'));
        return
      }
      messageApi.success('保存成功');
      onBack()
    } catch (error) {
      console.error('There was an error submitting the form!', error);
    }
  };

  const onReset = () => {
    setTitle('新增招聘岗位')
    form.resetFields();
  };
  
  const [enterpriseSelectorVisible, setEnterpriseSelectorVisible] = useState(false);
  const findEnterprise = () => {
    setEnterpriseSelectorVisible(true);
  }
  const handleEnterpriseSelected = (selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) => {
    setEnterpriseSelectorVisible(false)
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      enterpriseId: selectedEnterprise['enterpriseId'],
      enterpriseName: selectedEnterprise['enterpriseName'],
      }));
    }
  };
  const handleCloseEnterpriseSelector = () => {
    setEnterpriseSelectorVisible(false)
  };
  const [departmentSelectorVisible, setDepartmentSelectorVisible] = useState(false);
  const findDepartment = () => {
    setDepartmentSelectorVisible(true);
  }
  const handleDepartmentSelected = (selectedDepartment: { departmentId?: number; departmentName?: string; }) => {
    setDepartmentSelectorVisible(false)
    if (selectedDepartment && 'departmentId' in selectedDepartment) {
      form.setFieldsValue(Object.assign(form.getFieldsValue(), {
      departmentId: selectedDepartment['departmentId'],
      departmentName: selectedDepartment['departmentName'],
      }));
    }
  };
  const handleCloseDepartmentSelector = () => {
    setDepartmentSelectorVisible(false)
  };

  const onBack = () => {
    onCloseJobDescriptionAdd()
  };

  const addFooter = (
    <div className='custom-footer'>
      <Button type="primary" onClick={onSave}>保存</Button>
      <Button onClick={onReset} style={{marginLeft: 'var(--button-margin-left)'}}>重置</Button>
      <Button type="primary" onClick={onBack} style={{marginLeft: 'var(--button-margin-left)'}}>关闭</Button>
    </div>
  );

  return (
    <Modal title={title} open={visible} onCancel={onCloseJobDescriptionAdd} width={'var(--modal-width)'}
        footer={addFooter} style={{marginTop: 'var(--modal-margin-top)'}}>
      {messageContextHolder}
      <Form form={form} name="jobDescriptionForm" labelCol={{span: 6}}>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="enterpriseName" label="企业名称"  rules={rules.enterpriseName}>
              <Input.Search placeholder="请选择企业名称" onSearch={findEnterprise} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="jobTitle" label="岗位名称" rules={rules.jobTitle}>
              <Input maxLength={255} placeholder="请输入岗位名称"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="departmentName" label="部门名称"  rules={rules.departmentName}>
              <Input.Search placeholder="请选择部门名称" onSearch={findDepartment} readOnly={true} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="workLocation" label="工作地点" rules={rules.workLocation}>
              <Input maxLength={255} placeholder="请输入工作地点"/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="jobType" label="岗位类型" rules={rules.jobType}>
              <Select placeholder="请选择岗位类型" options={[
                { value: 10, label: <span>全职</span> },
                { value: 20, label: <span>兼职</span> },
                { value: 30, label: <span>实习</span> }
              ]} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="salaryRange" label="薪资范围" rules={rules.salaryRange}>
              <Select placeholder="请选择薪资范围" options={[
                { value: 1, label: <span>3000~5000</span> },
                { value: 2, label: <span>5001~10000</span> },
                { value: 3, label: <span>10001~20000</span> },
                { value: 4, label: <span>20001~30000</span> },
                { value: 5, label: <span>30000以上</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="postingDate" label="发布日期" rules={rules.postingDate}>
              <DatePicker/>
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="closingDate" label="截止日期">
              <DatePicker/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={11}>
            <Form.Item name="headCount" label="招聘人数" rules={rules.headCount}>
              <InputNumber min={1} max={1} />
            </Form.Item>
          </Col>
          <Col span={11}>
            <Form.Item name="status" label="状态" rules={rules.status}>
              <Select placeholder="请选择状态" options={[
                { value: 10, label: <span>开放</span> },
                { value: 20, label: <span>关闭</span> }
              ]} />
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={22}>
            <Form.Item name="responsibilities" label="岗位职责" labelCol={{span: 3}} rules={rules.responsibilities}>
              <Input.TextArea maxLength={65535} placeholder="请输入岗位职责" autoSize={{ minRows: 3, maxRows: 3 }}/>
            </Form.Item>
          </Col>
        </Row>
        <Row gutter={10}>
          <Col span={22}>
            <Form.Item name="requirement" label="岗位要求" labelCol={{span: 3}} rules={rules.requirement}>
              <Input.TextArea maxLength={65535} placeholder="请输入岗位要求" autoSize={{ minRows: 3, maxRows: 3 }}/>
            </Form.Item>
          </Col>
        </Row>
      </Form>
      <EnterpriseSelector visible={enterpriseSelectorVisible} onEnterpriseSelected={handleEnterpriseSelected} onCloseEnterpriseSelector={handleCloseEnterpriseSelector} />
      <DepartmentSelector visible={departmentSelectorVisible} onDepartmentSelected={handleDepartmentSelected} onCloseDepartmentSelector={handleCloseDepartmentSelector} />
    </Modal>
  )
}

export default JobDescriptionAdd;
